<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 品牌逻辑
 */
class Goods extends LogicBase
{
    /**
     * 数据状态设置
     */
    public function opStatus($param = null)
    {

        if (empty($param)) {

            return [RESULT_ERROR, '非法操作'];
        }

        $result = db('goods')->where('id',$param['id'])->update($param);;

        $result && action_log('商品数据状态', '商品数据状态');

        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];
    }
    /**
     * 导出会员列表
     */
    public function exportUserOrderList($where = [], $field = 'a.*,b.username,b.name,c.username as gusername,c.name as gname', $order = '')
    {
        $list = $this->getUserOrderList($where, $field, $order, false);
        foreach($list as $k=>$v){
            $list[$k]['pay']=getPay($v['pay']);
        }
        $titles = "用户名,昵称,订单号,收款用户,收款昵称,支付方式,订单金额,时间";
        $keys   = "username,name,order_sn,gusername,gname,pay,money,add_time";

        action_log('导出', '导出线下订单列表');

        export_excel($titles, $keys, $list, '线下订单列表');
    }
    /**
     * 订单列表
     */
    public function getUserOrderList($where = [], $field = 'a.*,b.username,b.name,c.username as gusername,c.name as gname', $order = 'a.id desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelOrder->alias('a');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'a.user_id = b.id', 'LEFT'],
            [SYS_DB_PREFIX . 'user c', 'a.getid = c.id', 'LEFT'],
        ];
        $this->modelOrder->join = $join;

        return $this->modelOrder->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取分类列表
     */
    public function getDianCatList($where = [], $field = '*', $order = '')
    {
        return $this->modelDianCat->getList($where, $field, $order);
    }
    /**
     * 获取品牌信息
     */
    public function getDianCatInfo($where = [], $field = '*')
    {
        return $this->modelDianCat->getInfo($where, $field);
    }
    /**
     * 品牌信息编辑
     */
    public function dianCatEdit($data = [])
    {

        $url = url('dianCatList');

        // empty($data['id']) && $data['member_id'] = MEMBER_ID;

        $result = $this->modelDianCat->setInfo($data);

        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '门店分类' . $handle_text . '，title：' . $data['title']);

        return $result ? [RESULT_SUCCESS, '门店分类操作成功', $url] : [RESULT_ERROR, $this->modelDianCat->getError()];
    }
    /**
     * 确认收货
     */
    public function qrsh($param){
        $info=db('order_info')->field('gid,danjia,num,order_sn,user_id')->where('id',$param['id'])->find();
        $stat=db('order_goods')->where(['order_sn'=>$info['order_sn']])->value('stat');
        if($stat != 1){
            return [RESULT_ERROR, '订单错误'];
        }
        db('order_info')->startTrans();
        $ginfo=db('goods')->field('user_id,city,county,bl,btbl,lrbl,pid,zt_money,jt_money')->where('id',$info['gid'])->find();
        $tjid=db('user')->where('id',$info['user_id'])->value('tjid');
        if($ginfo['tid'] == 1 && !empty($tjid)){
            moneyyj_log($ginfo['zt_money'],$tjid,23,$info['user_id'],$info['order_sn']);
            $tjjid=db('user')->where('id',$tjid)->value('tjid');
            if(!empty($tjjid)){
                moneyyj_log($ginfo['jt_money'],$tjjid,24,$info['user_id'],$info['order_sn']);
            }
            moneyyj_log($info['danjia']*$info['num']*$ginfo['bl'],$ginfo['user_id'],17,$info['user_id']);
        }else {
            fenrun($info['user_id'], $ginfo['user_id'], $info['danjia'] * $info['num'], $ginfo['lrbl'], $ginfo['btbl'], $ginfo['bl'], $ginfo['city'], $ginfo['county'], $tjid, $ginfo['pid']);
        }
        $res=db('order_info')->where('id',$param['id'])->update(['stat'=>2]);
        if($res != false){
            action_log('确认收货', '订单确认收货' . $info['order_sn'] . '，id：' . $param['id']);
            db('order_info')->commit();
            $url = url('orderList');
            return [RESULT_SUCCESS, '操作成功', $url];
        }else{
            db('order_info')->rollback();
            return [RESULT_ERROR, '操作失败'];
        }
    }
    /**
     * 撤销订单
     */
    public function cxOrder($param){
        $info=db('order_goods')->field('money,order_sn,pay,user_id')->where('id',$param['id'])->find();
        $order_sn=$info['order_sn'];
        $is=db('order_info')->where("order_sn='".$order_sn."' and stat != 0")->value('id');
        if(!empty($is)){
            return [RESULT_ERROR, '订单已发货，不能撤销'];
        }
       $res=db('order_goods')->where('id',$param['id'])->update(['stat'=>2]);
        if($res != false){
            action_log('撤销订单', '撤销订单' . $info['order_sn'] . '，id：' . $param['id']);
            if($info['pay'] == 1){
                $type=58;
            }elseif($info['pay'] == 3){
                $type=106;
            }else{
                $type=18;
            }
            moneyyj_log($info['money'],$info['user_id'],$type,$info['user_id'],$order_sn);
            db('order_goods')->commit();
            $url = url('orderList');
            return [RESULT_SUCCESS, '操作成功', $url];
        }else{
            db('order_goods')->rollback();
            return [RESULT_ERROR, '操作失败'];
        }
    }
	/**
     * 发货
     */
    public function fahuo($data = [])
    {
        
        $url = url('orderList');
        $data['stat']=1;
		$data['fh_time']=date('Y-m-d H:i:s');
        $result = $this->modelOrderInfo->setInfo($data);
		
        $handle_text = '发货';
        
        $result && action_log($handle_text, '订单商品发货' . $handle_text . '，gid：' . $data['gid']);
        
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelDian->getError()];
    }
	/**
     * 订单列表
     */
    public function getOrderList($where = [], $field = 'a.*,b.id as ids,b.money,b.zf_time,b.pay,c.username,c.name', $order = 'a.id desc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelOrderInfo->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'order_goods b', 'a.order_sn = b.order_sn', 'LEFT'],
					[SYS_DB_PREFIX . 'user c', 'b.user_id = c.id', 'LEFT'],
                ];        
        $this->modelOrderInfo->join = $join;
        
        return $this->modelOrderInfo->getList($where, $field, $order, $paginate);
    }
    /**
     * 导出会员列表
     */
    public function exportOrderList($where = [], $field = 'a.*,b.id as ids,b.money,b.zf_time,b.pay,b.name,b.phone,b.province,b.city,b.county,b.address,c.username,c.name as names', $order = 'a.id desc')
    {
        $list = $this->getOrderList($where, $field, $order, false);
        foreach($list as $k=>$v){
            $list[$k]['pay']=getPay($v['pay']);
            $list[$k]['stat']=$v['stat']==0?'待发货':($v['stat']==1?'待收货':'已确认收货');
            $list[$k]['shdz']=$v['province'].$v['city'].$v['county'].$v['address'];
        }
        $titles = "订单号,用户名,昵称,商品名,支付方式,订单总价,商品单价,购买数量,时间,状态,收货人,联系电话,收货地址";
        $keys   = "order_sn,username,names,title,pay,money,danjia,num,zf_time,stat,name,phone,shdz";

        action_log('导出', '导出线上订单列表');

        export_excel($titles, $keys, $list, '线上订单列表');
    }
    /**
     * 导出列表
     */
    public function exportDianList($where = [], $field = 'a.bl,a.btbl,a.lrbl,a.title,a.type,a.name,a.account,a.phone,a.status,b.username,b.name as names', $order = 'a.id desc')
    {
        $list = $this->getDianList($where, $field, $order, false);
        foreach($list as $k=>$v){
            $list[$k]['status']=$v['status']==0?'禁用':'启用';
            $list[$k]['str']=$v['bl'].'/'.$v['btbl'].'/'.$v['lrbl'];
            $list[$k]['account']=' '.$v['account'];
        }
        $titles = "用户名,昵称,店铺名称,账户类型,账户姓名,账户,联系电话,结算/补贴/平台利润,状态";
        $keys   = "username,names,title,type,name,account,phone,str,status";
        action_log('导出', '导出门店列表');
        export_excel($titles, $keys, $list, '门店列表');
    }
	/**
     * 删除门店
     */
    public function delDian($id)
    {
		$where=['id'=>$id];
        //$result = $this->modelAd->deleteInfo($where);
		$info=db('dian')->field('img_id,img_ids,user_id')->where($where)->find();
		//$img=get_picture_url($info['img_id']);
		$result = db('dian')->where($where)->delete();
		if($result){
			db('user')->where('id',$info['user_id'])->update(['is'=>0]);
//			//@unlink($_SERVER['DOCUMENT_ROOT'].$img);
//            //db('picture')->where('id',$info['img_id'])->delete();
//			if(!empty($info['img_ids'])){
//				$arr=explode(',',$info['img_ids']);
//				foreach($arr as $v){
//					$imgs=get_picture_url($v);
//					//@unlink($_SERVER['DOCUMENT_ROOT'].$imgs);
//                    //db('picture')->where('id',$v)->delete();
//				}
//			}
		}
        $result && action_log('删除', '删除门店，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '删除门店成功'] : [RESULT_ERROR, $this->modelDian->getError()];
    }
	/**
     * 获取商品列表
     */
    public function getDianList($where = [], $field = 'a.*,b.username,b.name as names', $order = 'a.id desc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelDian->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'a.user_id = b.id', 'LEFT'],
                ];
        
       // $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelDian->join = $join;
        
        return $this->modelDian->getList($where, $field, $order, $paginate);
    }

    /**
     * 根据地址 获取经纬度
     * @param $address
     * @return mixed
     */
    public function addresstolatlag($address){
        $url='http://restapi.amap.com/v3/geocode/geo?address='.$address.'&key=938e695afc1617ffccb76e520b21e527';
        if($result=file_get_contents($url))
        {
            $result = json_decode($result,true);
            //判断是否成功
            if(!empty($result['count'])){
                return  explode(',',$result['geocodes']['0']['location']);
            }else{
                return false;
            }
        }
    }
	/**
     * 门店编辑
     */
    public function dianEdit($data = [])
    {
        
        $validate_result = $this->validateDian->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateDian->getError()];
        }
        $url = url('dianList');
       // empty($data['id']) && $data['member_id'] = MEMBER_ID;
       // $data['content'] = html_entity_decode($data['content']);
        if(empty($data['bl']) || empty($data['btbl']) || empty($data['lrbl'])){
            return [RESULT_ERROR, '请输入比例'];
        }
        if($data['bl']+$data['btbl']+$data['lrbl'] != 1){
            return [RESULT_ERROR, '请输入正确分配比例'];
        }
        $s=$this->addresstolatlag($data['province'].$data['city'].$data['county'].$data['address']);
        $data['x']=$s[1];
        $data['y']=$s[0];
        $data['create_time']=date('Y-m-d H:i:s');
		if(empty($data['id'])){
            $data['user_id']=db('user')->where('username',$data['username'])->value('id');
            if(empty($data['user_id'])){
                return [RESULT_ERROR, '不存在该用户'];
            }
			db('user')->where('id',$data['user_id'])->update(['is'=>1]);

		}
        $result = $this->modelDian->setInfo($data);
        $handle_text = empty($data['id']) ? '新增' : '编辑';
        $result && action_log($handle_text, '门店' . $handle_text . '，title：' . $data['title']);
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelDian->getError()];
    }

	
	/**
     * 充值状态设置
     */
    public function updateStats($data)
    {
		$info=db('apply')->where('id',$data['id'])->find();
		if(empty($info) || $info['status'] != 0){
			return  json_encode(array('error'=>1,'msg'=>'参数错误'));
		}
		$data['op_time']=time();
		$res=db('apply')->where('id',$data['id'])->update($data);
		
		//推送
		//jpush(strval($info['user_id']),2,'您的提现申请已转款，请查收！');
			
        $res && action_log('商品试用申请状态', '商品试用申请状态' . '，id：' . $data['id'] . '，status：' . $data['status']);        
        return $res ? json_encode(array('error'=>0,'msg'=>'操作成功')) : json_encode(array('error'=>1,'msg'=>'操作失败'));
    }
	/**
     * 品牌信息编辑
     */
    public function GoodsEdit($data = [])
    {
        
        $validate_result = $this->validateGoods->scene('edit')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateGoods->getError()];
        }
        
        $url = url('goodsList');
        if(empty($data['bl']) || empty($data['btbl']) || empty($data['lrbl'])){
            return [RESULT_ERROR, '请输入比例'];
        }
        $s=floatval($data['lrbl'])+floatval($data['btbl'])+floatval($data['bl']);

        if( $s != floatval(1)){
            return [RESULT_ERROR, '请输入正确分配比例'];
        }
        $data['pid']=db('goods_cat')->where('id',$data['catid'])->value('pid');
        if(!empty($data['pid'])){
            $data['tid']=db('goods_cat')->where('id',$data['pid'])->value('pid');
            if(empty($data['tid'])){
                //return [RESULT_ERROR, '请选择三级分类'];
            }
        }else{
            return [RESULT_ERROR, '请选择三级分类'];
        }
        if(empty($data['id'])){
            $where=['username'=>$data['username']];
            $data['user_id']=db('user')->where($where)->value('id');
            if(empty($data['user_id'])){
                return [RESULT_ERROR, '不存在该用户'];
            }
            $data['create_time']=date('Y-m-d H:i:s');
        }
        // empty($data['id']) && $data['member_id'] = MEMBER_ID;
        
        $data['content'] = html_entity_decode($data['content']);

        $result = $this->modelGoods->setInfo($data);
        if($result && $data['is_xx'] == 1 && !empty($result)){
            db('user')->where('id',$data['user_id'])->update(['is'=>1]);
        }
        $handle_text = empty($data['id']) ? '新增' : '编辑';
        
        $result && action_log($handle_text, '商品' . $handle_text . '，title：' . $data['title']);
        
        return $result ? [RESULT_SUCCESS, '商品操作成功', $url] : [RESULT_ERROR, $this->modelGoods->getError()];
    }
	/**
     * 获取品牌信息
     */
    public function getGoodsInfo($where = [], $field = '*')
    {
        return $this->modelGoods->getInfo($where, $field);
    }
    /**
     * 获取商品列表
     */
    public function getGoodsList($where = [], $field = 'a.*,b.title as titles,c.username,c.name', $order = 'a.id desc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelGoods->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'goods_cat b', 'a.catid = b.id', 'LEFT'],
                    [SYS_DB_PREFIX . 'user c', 'a.user_id = c.id', 'LEFT'],
                ];
        
       // $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelGoods->join = $join;
        
        return $this->modelGoods->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取分类列表
     */
    public function getGoodsCatList($where = ['pid'=>0], $field = '*', $order = '')
    {        
        return $this->modelGoodsCat->getList($where, $field, $order);
    }
    
    /**
     * 获取品牌列表搜索条件
     */
    public function getWhere($data = [])
    {
        
        $where = [];
        isset($data['catid']) && $where['a.catid']=$data['catid'];
        !empty($data['search_data']) && $where['a.title|b.title'] = ['like', '%'.$data['search_data'].'%'];
        
        return $where;
    }
    
    /**
     * 品牌信息编辑
     */
    public function goodsCatEdit($data = [])
    {
        
        $validate_result = $this->validateGoodsCat->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateGoodsCat->getError()];
        }
        
        $url = url('goodsCatList');
        $level=db('goods_cat')->where('id',$data['pid'])->value('level');
       // empty($data['id']) && $data['member_id'] = MEMBER_ID;
        $data['level']=$level+1;
        if($data['id'] == 1){
            return [RESULT_ERROR,'不能修改'];
        }
        $result = $this->modelGoodsCat->setInfo($data);
        
        $handle_text = empty($data['id']) ? '新增' : '编辑';
        
        $result && action_log($handle_text, '商品分类' . $handle_text . '，title：' . $data['title']);
        
        return $result ? [RESULT_SUCCESS, '商品分类操作成功', $url] : [RESULT_ERROR, $this->modelAd->getError()];
    }

    /**
     * 获取品牌信息
     */
    public function getGoodsCatInfo($where = [], $field = '*')
    {
        return $this->modelGoodsCat->getInfo($where, $field);
    }
    /**
     * 分类删除
     */
    public function goodsCatDel($id)
    {
        $is=db('goods')->where('catid',$id)->value('id');
		if(!empty($is) || $id == 1){
			return [RESULT_ERROR, '该商品分类下存在商品，不能删除'];
		}
		//$cover_id=db('goods_cat')->where(['id' => $id])->value('img_id');
		//$img=get_picture_url($cover_id);
		$result = db('goods_cat')->where(['id' => $id])->delete();
        $result && action_log('商品分类删除', '商品分类删除，where：' . http_build_query(['id' => $id]));
       // $result && @unlink($_SERVER['DOCUMENT_ROOT'].$img);
        return $result ? [RESULT_SUCCESS, '商品分类删除成功'] : [RESULT_ERROR, $this->modelGoodsCat->getError()];
    }
	/**
     * 品牌删除
     */
    public function delGoods($id)
    {
		$is=db('order_info')->where('gid',$id)->value('id');
		if(!empty($is)){
			return [RESULT_ERROR, '该商品已生成订单，不能删除'];
		}
		$where=['id'=>$id];
        //$result = $this->modelAd->deleteInfo($where);
		//$info=db('goods')->field('img_id,img_ids,cont_ids')->where($where)->find();
		//$img=get_picture_url($info['img_id']);
		$result = db('goods')->where($where)->delete();
//		if($result){
//			//@unlink($_SERVER['DOCUMENT_ROOT'].$img);
//           // db('picture')->where('id',$info['img_id'])->delete();
//			if(!empty($info['img_ids'])){
//				$arr=explode(',',$info['img_ids']);
//				foreach($arr as $v){
//					$imgs=get_picture_url($v);
//					//@unlink($_SERVER['DOCUMENT_ROOT'].$imgs);
//                   // db('picture')->where('id',$v)->delete();
//				}
//			}
//			if(!empty($info['cont_ids'])){
//				$arrs=explode(',',$info['cont_ids']);
//				foreach($arrs as $v){
//					$imgs=get_picture_url($v);
//					//@unlink($_SERVER['DOCUMENT_ROOT'].$imgs);
//                    //db('picture')->where('id',$v)->delete();
//				}
//			}
//		}
        $result && action_log('删除', '商品删除，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '商品删除成功'] : [RESULT_ERROR, $this->modelGoods->getError()];
    }
}
